<template>
  <div class="app">
    <!-- 检查当前路由是否是登录页 -->
    <template v-if="!isLoginPage">
      <el-container style="height: 100vh; display: flex;">
        <el-aside :width="sidebarWidth" class="sidebar" :class="{ 'sidebar-collapsed': isCollapsed }">
          <div class="logo">
            <h2 v-show="!isCollapsed">设备管理系统</h2>
            <h2 v-show="isCollapsed" class="collapsed-logo">设备</h2>
          </div>
          <el-menu 
            :default-openeds="['1']" 
            router 
            class="menu" 
            active-text-color="#667eea"
            :collapse="isCollapsed"
          >
            <el-menu-item index="/" class="menu-item">
              <el-icon><HomeFilled /></el-icon>
              <span>首页</span>
            </el-menu-item>
            <el-sub-menu index="1" class="menu-sub">
              <template #title>
                <el-icon><Management /></el-icon>
                <span>产品管理</span>
              </template>
              <el-menu-item index="/product-types" class="menu-item">
                <el-icon><Menu /></el-icon>
                <span>产品类型管理</span>
              </el-menu-item>
              <el-menu-item index="/products" class="menu-item">
                <el-icon><Goods /></el-icon>
                <span>产品管理</span>
              </el-menu-item>
            </el-sub-menu>
            <el-menu-item index="/devices" class="menu-item">
              <el-icon><Monitor /></el-icon>
              <span>设备管理</span>
            </el-menu-item>
            <el-menu-item index="/login-records" class="menu-item">
              <el-icon><View /></el-icon>
              <span>登录记录</span>
            </el-menu-item>
          </el-menu>
        </el-aside>
        <el-container style="display: flex; flex-direction: column; flex: 1;">
          <el-header class="header">
            <div class="header-left">
              <el-button 
                class="sidebar-toggle" 
                @click="toggleSidebar"
                :icon="isCollapsed ? 'Expand' : 'Fold'"
                circle
                size="small"
              />
              <h1 class="page-title">{{ getPageTitle }}</h1>
            </div>
            <div class="user-info">
              <el-dropdown>
                <span class="el-dropdown-link">
                  <!-- 用户头像 -->
                  <div class="user-avatar">
                    <img v-if="userStore.avatar" :src="userStore.avatar" alt="用户头像" class="avatar-image" />
                    <div v-else class="avatar-text">{{ getDefaultAvatarText(userStore.username) }}</div>
                  </div>
                  {{ userStore.username }}
                  <el-icon class="el-icon--right"><ArrowDown /></el-icon>
                </span>
                <template #dropdown>
                  <el-dropdown-menu>
                    <el-dropdown-item @click="goToProfile">
                      <el-icon><UserFilled /></el-icon>
                      <span>个人中心</span>
                    </el-dropdown-item>
                    <el-dropdown-item @click="logout">
                      <el-icon><SwitchButton /></el-icon>
                      <span>退出登录</span>
                    </el-dropdown-item>
                  </el-dropdown-menu>
                </template>
              </el-dropdown>
            </div>
          </el-header>
          <el-main class="main-content">
            <RouterView />
          </el-main>
        </el-container>
      </el-container>
    </template>
    <!-- 登录页面 -->
    <template v-else>
      <RouterView />
    </template>
    
    <!-- 通知堆叠组件 -->
    <NotificationStack ref="notificationStackRef" />
  </div>
</template>

<script setup>
import { computed, inject, onMounted, ref } from 'vue'
import { useRoute, useRouter } from 'vue-router'
// 导入正确的图标
import { HomeFilled, Management, Monitor, UserFilled, ArrowDown, Menu, Goods, SwitchButton, View, Expand, Fold } from '@element-plus/icons-vue'
import NotificationStack from './components/NotificationStack.vue'
import notificationService from './utils/notificationService.js'
import authAPI from './api/auth.js'

const route = useRoute()
const router = useRouter()

// 注入用户状态管理
const userStore = inject('userStore')

// 侧边栏收起状态
const isCollapsed = ref(false)

// 侧边栏宽度计算
const sidebarWidth = computed(() => {
  return isCollapsed.value ? '64px' : '220px'
})

// 切换侧边栏收起状态
const toggleSidebar = () => {
  isCollapsed.value = !isCollapsed.value
}

// 通知组件引用
const notificationStackRef = ref(null)

// 检查是否是登录页面或404页面
const isLoginPage = computed(() => {
  return route.path === '/login' || route.name === 'NotFound'
})

// 获取页面标题
const getPageTitle = computed(() => {
  const titles = {
    '/': '首页',
    '/product-types': '产品类型管理',
    '/products': '产品管理',
    '/devices': '设备管理',
    '/login-records': '登录记录'
  }
  return titles[route.path] || '设备管理系统'
})

// 跳转到个人中心
const goToProfile = () => {
  router.push('/profile')
}
  
  // 退出登录
  const logout = async () => {
    try {
      // 调用后端退出登录接口
      await authAPI.logout();
    } catch (error) {
      console.error('退出登录API调用失败:', error);
      // 即使API调用失败，仍然进行本地清理
    } finally {
      // 清除本地存储的用户信息和token
      localStorage.removeItem('userInfo')
      localStorage.removeItem('accessToken')
      localStorage.removeItem('refreshToken')
      // 重置状态
      userStore.username = '管理员'
      userStore.avatar = ''
      notificationService.success('已退出登录')
      // 重定向到登录页
      router.push('/login')
    }
  }

// 获取用户的第一个字符作为默认头像
const getDefaultAvatarText = (name) => {
  return name ? name.charAt(0).toUpperCase() : '管'
}

// 组件挂载后将通知组件引用传递给服务
onMounted(() => {
  if (notificationStackRef.value) {
    notificationService.setNotificationStack(notificationStackRef.value)
  }
})
</script>

<style>
* {
  margin: 0;
  padding: 0;
}

html, body {
  height: 100%;
  font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, 'Helvetica Neue', Arial, sans-serif;
  -webkit-font-smoothing: antialiased;
  -moz-osx-font-smoothing: grayscale;
}

#app {
  height: 100%;
}

.app {
  height: 100%;
  background: linear-gradient(135deg, #f5f7fa 0%, #c3cfe2 100%);
}

/* 侧边栏样式 */
.sidebar {
  background: linear-gradient(180deg, #ffffff 0%, #f8f9fa 100%);
  border-right: 1px solid #e9ecef;
  box-shadow: 2px 0 8px rgba(0, 0, 0, 0.05);
  transition: all 0.3s cubic-bezier(0.4, 0, 0.2, 1);
  overflow: hidden;
  will-change: width;
}

/* 侧边栏收起状态 */
.sidebar-collapsed {
  width: 64px !important;
}

.sidebar-collapsed .logo {
  padding: 17px 8px;
}

.sidebar-collapsed .collapsed-logo {
  font-size: 14px;
  margin: 0;
  text-align: center;
  line-height: 1;
}

.logo {
  padding: 17px;
  text-align: center;
  border-bottom: 1px solid #e9ecef;
  background: linear-gradient(90deg, #667eea 0%, #764ba2 100%);
}

.logo h2 {
  margin: 0;
  font-size: 18px;
  font-weight: bold;
  color: white;
}

/* 菜单样式 */
.menu {
  border-right: none;
  background: transparent;
  padding-top: 0;
}

.menu-item {
  transition: all 0.3s cubic-bezier(0.4, 0, 0.2, 1);
  border-left: 3px solid transparent;
  margin: 4px 0;
  font-weight: 500;
  will-change: transform, background-color;
}

.menu-item:hover {
  background-color: rgba(102, 126, 234, 0.05);
  border-left-color: rgba(102, 126, 234, 0.5);
  transform: translateX(4px);
}

.menu-item.is-active {
  background-color: rgba(102, 126, 234, 0.1);
  border-left-color: #667eea;
}

.menu-sub .el-sub-menu__title {
  transition: all 0.3s cubic-bezier(0.4, 0, 0.2, 1);
  border-left: 3px solid transparent;
  margin: 4px 0;
  font-weight: 500;
  will-change: transform, background-color;
}

.menu-sub .el-sub-menu__title:hover {
  background-color: rgba(102, 126, 234, 0.05);
  border-left-color: rgba(102, 126, 234, 0.5);
  transform: translateX(4px);
}

/* 页眉样式 */
.header {
  background: linear-gradient(90deg, #667eea 0%, #764ba2 100%);
  color: white;
  box-shadow: 0 2px 10px rgba(0, 0, 0, 0.1);
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 0 20px;
  height: 50px;
  position: relative;
  z-index: 10;
}

.header-left {
  display: flex;
  align-items: center;
  gap: 16px;
}

.sidebar-toggle {
  background: rgba(255, 255, 255, 0.2) !important;
  border: 1px solid rgba(255, 255, 255, 0.3) !important;
  color: white !important;
  transition: all 0.3s ease;
}

.sidebar-toggle:hover {
  background: rgba(255, 255, 255, 0.3) !important;
  transform: scale(1.05);
}

.page-title {
  margin: 0;
  font-size: 18px;
  font-weight: 600;
  color: white;
}

/* 用户信息样式 */
  .user-info {
    display: flex;
    align-items: center;
  }

  /* 用户头像样式 */
  .user-avatar {
    width: 36px;
    height: 36px;
    border-radius: 50%;
    overflow: hidden;
    margin-right: 8px;
    display: inline-flex;
    align-items: center;
    justify-content: center;
    vertical-align: middle;
    background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
    color: white;
    font-weight: bold;
    box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1);
    transition: transform 0.2s ease;
  }

  .user-avatar:hover {
    transform: scale(1.05);
  }

  .avatar-image {
    width: 100%;
    height: 100%;
    object-fit: cover;
  }

  .avatar-text {
    font-size: 16px;
    line-height: 1;
  }

.user-info .el-dropdown {
  color: white;
  cursor: pointer;
}

.user-info .el-dropdown-link {
  color: white;
  text-decoration: none;
  display: flex;
  align-items: center;
}

.user-info .el-dropdown-link:hover {
  color: #f0f0f0;
}

.user-info .el-dropdown-menu {
  background-color: white;
  color: #303133;
  border-radius: 4px;
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
}

.user-info .el-dropdown-item {
  color: #303133;
  font-size: 14px;
  padding: 8px 20px;
}

.user-info .el-dropdown-item:hover {
  background-color: #f5f7fa;
  color: #667eea;
}

.el-dropdown-link {
  display: flex;
  align-items: center;
  color: #606266;
  cursor: pointer;
  padding: 8px 12px;
  border-radius: 6px;
  transition: all 0.3s ease;
}

.el-dropdown-link:hover {
  background-color: rgba(102, 126, 234, 0.05);
  color: #667eea;
}

/* 主内容区域样式 */
.main-content {
  flex: 1;
  overflow: auto;
  padding: 0;
  background: transparent;
  transition: margin-left 0.3s cubic-bezier(0.4, 0, 0.2, 1);
  will-change: margin-left;
}

/* 滚动条样式 */
::-webkit-scrollbar {
  width: 8px;
  height: 8px;
}

::-webkit-scrollbar-track {
  background: #f1f1f1;
  border-radius: 4px;
}

::-webkit-scrollbar-thumb {
  background: #c1c1c1;
  border-radius: 4px;
  transition: background 0.3s ease;
}

::-webkit-scrollbar-thumb:hover {
  background: #a8a8a8;
}

/* 响应式调整 */
@media (max-width: 768px) {
  .sidebar {
    width: 180px !important;
  }
  
  .sidebar-collapsed {
    width: 64px !important;
  }
  
  .logo h2 {
    font-size: 16px;
  }
  
  .collapsed-logo {
    font-size: 12px !important;
  }
  
  .page-title {
    font-size: 18px;
  }
  
  .header {
    padding: 0 16px;
  }
  
  .header-left {
    gap: 12px;
  }
  
  .sidebar-toggle {
    width: 32px !important;
    height: 32px !important;
  }
}

@media (max-width: 480px) {
  .sidebar {
    width: 160px !important;
  }
  
  .sidebar-collapsed {
    width: 56px !important;
  }
  
  .menu-item span,
  .menu-sub .el-sub-menu__title span {
    font-size: 14px;
  }
  
  .page-title {
    font-size: 16px;
  }
  
  .header {
    padding: 0 12px;
  }
  
  .header-left {
    gap: 8px;
  }
  
  .sidebar-toggle {
    width: 28px !important;
    height: 28px !important;
  }
  
  .collapsed-logo {
    font-size: 10px !important;
  }
}
</style>
